package com.ruoyi.common.core.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.ruoyi.common.core.utils.uuid.UUID;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class QRCodeGenerator {
    @Value("${oss.endpoint}")
    private  String endpoint;

    @Value("${oss.accessKeyId}")
    private String accessKeyId;

    @Value("${oss.accessKeySecret}")
    private  String accessKeySecret;

    @Value("${oss.bucketName}")
    private  String bucketName;

    @Value("${oss.furl}")
    private String furl;
//    private static final String ENDPOINT = "https://oss-cn-beijing.aliyuncs.com";
//    private static final String ACCESS_KEY_ID = "LTAI5tFrW5fuwmK27RSXzmx1";
//    private static final String ACCESS_KEY_SECRET = "6RIOAjArzhNfFty5kPXcRPMCwTYzWI";
//    private static final String BUCKET_NAME = "car-service01";
    private static final String OBJECT_NAME_PREFIX = "images/";

    private static void generateQRCodeImage(String text, int width, int height, String filePath) throws WriterException, IOException {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height, hints);
        Path path = FileSystems.getDefault().getPath(filePath);
        MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);
    }

    public String generateQRCode(String text) {
        // 获取当日日期作为目录名
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        String date = dateFormat.format(new Date());
        // 构建本地目录
        String localDir = "image/" + date + "/";
        File localDirFile = new File(localDir);
        if (!localDirFile.exists()) {
            if (!localDirFile.mkdirs()) {
                System.err.println("无法创建本地目录: " + localDir);
                return null;
            }
        }

        // 利用UUID生成文件名
        String s = UUID.randomUUID() + ".png";
        // 构建本地文件路径
        String localFilePath = localDir + s;

        try {
            // 先在本地生成二维码图片
            generateQRCodeImage(text, 350, 350, localFilePath);

            System.out.println("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&");
            System.out.println("endpoint = " + endpoint);
            System.out.println("accessKeyId = " + accessKeyId);
            System.out.println("accessKeySecret = " + accessKeySecret);
            System.out.println("bucketName = " + bucketName);
            System.out.println("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&");

            // 创建 OSS 客户端实例
            OSS oss = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            // 构建 OSS 上的文件路径
            String ossObjectName = OBJECT_NAME_PREFIX + date + s;
            // 上传本地图片到 OSS
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, ossObjectName, new File(localFilePath));
            PutObjectResult putObjectResult = oss.putObject(putObjectRequest);

            // 关闭 OSS 客户端
            oss.shutdown();

            System.out.println("UUID = " + s);
            System.out.println("路径为：" + "https://" + bucketName + ".oss-cn-beijing.aliyuncs.com/" + ossObjectName);
            // 返回 OSS 上的图片 URL
            return "https://" + bucketName + ".oss-cn-beijing.aliyuncs.com/" + ossObjectName;
        } catch (WriterException | IOException e) {
            System.err.println("生成二维码时出现错误：" + e.getMessage());
        } catch (Exception e) {
            System.err.println("上传二维码到 OSS 时出现错误：" + e.getMessage());
        }
        return null;
    }
}